﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Acms.AcmsControls.ContentControls.FrontEnd;
using Acms.Bll;


namespace Ait.Web.Templates.Home
{
    public partial class _default : Acms.AcmsControls.TemplatePage
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            dsLatestNews.SelectData += new EventHandler<Acms.DataControls.SelectEventArgs<Acms.Bll.Post>>(dsLatestNews_SelectData);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataBind();
                
                Random rnd = new Random();

                int randomNumber = rnd.Next(1, 5);
                
                switch (randomNumber)
                {
                    case 1:
                        phQuote1.Visible = true;
                        break;
                    case 2:
                        phQuote2.Visible = true;
                        break;
                    case 3:
                        phQuote3.Visible = true;
                        break;
                    case 4:
                        phQuote4.Visible = true;
                        break;
                    case 5:
                        phQuote5.Visible = true;
                        break;
                }
                //var post = e.DataItem as Post;

                //var tmp = .FindControl("phQuote1");
                //if(tmp == null)
                //    throw new Exception("Its " + tmp.GetType().ToString());
                    
               
                    //phQuote.Visible = true;
               
            }
        }

        protected void dsLatestNews_SelectData(object sender, Acms.DataControls.SelectEventArgs<Acms.Bll.Post> e)
        {
            var latestNews = new List<Post>();
            if (AcmsContext.CurrentPost != null)
            {
                var aboutpost = AcmsContext.CurrentPost.FindChildByName("About-AIT");
                GetLatestNews(aboutpost.Children, latestNews);
            }

            e.SetData(latestNews);
        }

        private void GetLatestNews(IEnumerable<Post> posts, List<Post> latestNews)
        {
            if (posts == null)
                return;

            foreach (var post in posts)
            {
                if (post.TemplateName == "NewsItem")
                {
                    latestNews.Add(post);
                    
                }
            }
            foreach (var post in posts)
            {
                GetLatestNews(post.Children, latestNews);
            }
        }
    }
}
